<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生餐费统计</title>
    <link rel="stylesheet" href="/scriptZIP/indexPlus.css">
    <style>
        [v-cloak] {
            display: none;
        }

        .statistics {
            margin-bottom: 20px;
        }

        .statistics .el-tag {
            font-size: 16px;
            margin-right: 10px;
            height: 32px;
            line-height: 32px;
            padding: 0 10px;
        }

        .filter-container {
            margin: 20px 0;
        }

        .submit-btn {
            margin-top: 20px;
            text-align: center;
        }

        .date-range-picker {
            width: 300px;
        }
    </style>
</head>

<body>
    <div id="app" v-cloak>
        <h2>学生餐费统计</h2>

        <!-- 学生信息 -->
        <el-card>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="校区">
                        <span>{{ student.schoolName }}</span>
                    </el-form-item>
                    <el-form-item label="学生姓名">
                        <span>{{ student.name }}</span>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-card>

        <!-- 统计信息 -->
        <div class="statistics">
            <el-tag type="success">已收费午餐: {{ paidLunchCount }}</el-tag>
            <el-tag type="info">已收费晚餐: {{ paidDinnerCount }}</el-tag>
            <el-tag type="warning">未收费午餐: {{ unpaidLunchCount }}</el-tag>
            <el-tag type="danger">未收费晚餐: {{ unpaidDinnerCount }}</el-tag>
        </div>

        <!-- 时间筛选 -->
        <div class="filter-container">
            <el-date-picker v-model="dateRange" type="monthrange" class="date-range-picker" range-separator="至"
                start-placeholder="开始月份" end-placeholder="结束月份" format="YYYY-MM" value-format="YYYY-MM"
                @change="handleDateRangeChange" />
        </div>

        <!-- 报餐记录 -->
        <el-table :data="mealRecords" border style="width: 100%">
            <el-table-column prop="date" label="日期" width="120"></el-table-column>

            <el-table-column label="午餐收费状态">
                <template #header>
                    <el-checkbox :model-value="isLunchAllChecked" @change="toggleAllLunch"
                        :indeterminate="isLunchIndeterminate">
                        全选（{{ filteredLunchCount }}项）
                    </el-checkbox>
                </template>
                <template #default="scope">
                    <span v-if="scope.row.lunchId === null">未报餐</span>
                    <el-checkbox v-else v-model="scope.row.lunchCharge"
                        @change="handleSingleChange(scope.row, 'lunch')">
                        {{ scope.row.lunchCharge ? '已收费' : '未收费' }}
                    </el-checkbox>
                </template>
            </el-table-column>

            <el-table-column label="晚餐收费状态">
                <template #header>
                    <el-checkbox :model-value="isDinnerAllChecked" @change="toggleAllDinner"
                        :indeterminate="isDinnerIndeterminate">
                        全选（{{ filteredDinnerCount }}项）
                    </el-checkbox>
                </template>
                <template #default="scope">
                    <span v-if="scope.row.dinnerId === null">未报餐</span>
                    <el-checkbox v-else v-model="scope.row.dinnerCharge"
                        @change="handleSingleChange(scope.row, 'dinner')">
                        {{ scope.row.dinnerCharge ? '已收费' : '未收费' }}
                    </el-checkbox>
                </template>
            </el-table-column>
        </el-table>

        <!-- 提交按钮 -->
        <div class="submit-btn">
            <el-button type="primary" @click="submitChanges" :loading="submitting">
                提交变更（{{ changesCount }}项）
            </el-button>
        </div>
    </div>

    <script src="/scriptZIP/vue.global.js"></script>
    <script src="/scriptZIP/index.full.js"></script>
    <script src="/scriptZIP/axios.min.js"></script>
    <script src="/scriptZIP/zh-cn-plus.js"></script>
    <script>
        const { createApp } = Vue;
        createApp({
            data() {
                return {
                    student: {},
                    lunch: [],
                    dinner: [],
                    dateRange: [],
                    originalLunch: [],
                    originalDinner: [],
                    submitting: false
                };
            },
            computed: {
                // 过滤后的数据
                filteredLunch() {
                    return this.filterByDateRange(this.lunch);
                },
                filteredDinner() {
                    return this.filterByDateRange(this.dinner);
                },

                // 表格数据
                mealRecords() {
                    const lunchDates = this.filteredLunch.map(l => l.date);
                    const dinnerDates = this.filteredDinner.map(d => d.date);
                    const allDates = [...new Set([...lunchDates, ...dinnerDates])]
                        .sort((a, b) => new Date(b) - new Date(a));

                    return allDates.map(date => {
                        const lunch = this.filteredLunch.find(l => l.date === date) || {};
                        const dinner = this.filteredDinner.find(d => d.date === date) || {};
                        return {
                            date,
                            lunchCharge: lunch.charge || false,
                            lunchId: lunch.id || null,
                            dinnerCharge: dinner.charge || false,
                            dinnerId: dinner.id || null,
                        };
                    });
                },

                // 统计信息
                paidLunchCount() {
                    return this.filteredLunch.filter(item => item.charge).length;
                },
                unpaidLunchCount() {
                    return this.filteredLunch.filter(item => !item.charge).length;
                },
                paidDinnerCount() {
                    return this.filteredDinner.filter(item => item.charge).length;
                },
                unpaidDinnerCount() {
                    return this.filteredDinner.filter(item => !item.charge).length;
                },

                // 全选状态
                isLunchAllChecked() {
                    const valid = this.filteredLunch.filter(item => item.id);
                    return valid.length > 0 && valid.every(item => item.charge);
                },
                isLunchIndeterminate() {
                    const valid = this.filteredLunch.filter(item => item.id);
                    return valid.some(item => item.charge) && !this.isLunchAllChecked;
                },
                isDinnerAllChecked() {
                    const valid = this.filteredDinner.filter(item => item.id);
                    return valid.length > 0 && valid.every(item => item.charge);
                },
                isDinnerIndeterminate() {
                    const valid = this.filteredDinner.filter(item => item.id);
                    return valid.some(item => item.charge) && !this.isDinnerAllChecked;
                },

                // 可操作项数量
                filteredLunchCount() {
                    return this.filteredLunch.filter(item => item.id).length;
                },
                filteredDinnerCount() {
                    return this.filteredDinner.filter(item => item.id).length;
                },

                // 变更数量
                changesCount() {
                    return this.getChangedRecords().length;
                }
            },
            methods: {
                // 初始化参数
                getParams() {
                    const params = {};
                    location.search.substring(1).split('&').forEach(pair => {
                        const [key, value] = pair.split('=');
                        params[key] = decodeURIComponent(value);
                    });
                    return params;
                },

                // 日期范围过滤
                filterByDateRange(list) {
                    if (this.dateRange.length !== 2) return list;

                    const [start, end] = this.dateRange;
                    return list.filter(item => {
                        const date = new Date(item.date);
                        return date >= new Date(start + '-01') &&
                            date <= new Date(end + '-31');
                    });
                },

                // 全选操作
                toggleAllLunch(checked) {
                    const targets = this.dateRange.length === 2
                        ? this.filteredLunch
                        : this.lunch;

                    targets.forEach(item => {
                        if (item.id) item.charge = checked;
                    });
                },
                toggleAllDinner(checked) {
                    const targets = this.dateRange.length === 2
                        ? this.filteredDinner
                        : this.dinner;

                    targets.forEach(item => {
                        if (item.id) item.charge = checked;
                    });
                },

                // 单个修改处理
                handleSingleChange(row, type) {
                    const original = type === 'lunch'
                        ? this.originalLunch.find(item => item.id === row[type + 'Id'])
                        : this.originalDinner.find(item => item.id === row[type + 'Id']);

                    if (original && original.charge === row[type + 'Charge']) {
                        this.$forceUpdate();
                    }
                },

                // 获取变更记录
                getChangedRecords() {
                    return [
                        ...this.lunch.filter(item =>
                            this.originalLunch.some(o =>
                                o.id === item.id && o.charge !== item.charge
                            )
                        ),
                        ...this.dinner.filter(item =>
                            this.originalDinner.some(o =>
                                o.id === item.id && o.charge !== item.charge
                            )
                        )
                    ].map(({ id, charge }) => ({ id, charge }));
                },

                // 提交变更
                async submitChanges() {
                    this.submitting = true;
                    const changes = this.getChangedRecords();

                    if (changes.length === 0) {
                        this.$message.warning('没有变更需要提交');
                        this.submitting = false;
                        return;
                    }

                    try {
                        await axios.post('/pc/mealReservation/updateMealCharges', changes);
                        this.$message.success(`成功提交 ${changes.length} 项变更`);
                        this.updateOriginalData();
                    } catch (error) {
                        this.$message.error('提交失败');
                        console.error(error);
                    } finally {
                        this.submitting = false;
                    }
                },

                // 更新原始数据
                updateOriginalData() {
                    this.originalLunch = JSON.parse(JSON.stringify(this.lunch));
                    this.originalDinner = JSON.parse(JSON.stringify(this.dinner));
                },

                // 日期范围变化处理
                handleDateRangeChange() {
                    this.$forceUpdate();
                }
            },
            async created() {
                const id = this.getParams().id;
                try {
                    const res = await axios.get(`/pc/mealReservation/studentMeal/${id}`);
                    this.student = {
                        schoolName: res.data.schoolName,
                        name: res.data.name
                    };
                    this.lunch = res.data.lunch;
                    this.dinner = res.data.dinner;
                    this.updateOriginalData();
                } catch (error) {
                    this.$message.error('数据加载失败');
                    console.error(error);
                }
            }
        }).use(ElementPlus,{locale: ElementPlusLocaleZhCn}).mount("#app");
    </script>
</body>

</html>